import React from "react";
import * as XLSX from "xlsx";

export default function Export() {
  const importExcelToJson = (file) => {
    // Construct a FileReader object to read the file
    const fileReader = new FileReader();
    const rABS = !!fileReader.readAsBinaryString;
    // Return Promise to facilitate the delivery of processed json to back-end processing
    return new Promise((resolve, reject) => {
      fileReader.onerror = () => {
        fileReader.abort();
        reject("Failed to read the file");
      };
      fileReader.onload = () => {
        try {
          // Deconstruct the result read by fileReader to result
          const { result } = fileReader;
          // Use XLSX to read binary stream to generate workbook
          const stores = XLSX.read(result, { type: rABS ? "binary" : "array" });
          let data = [];
          // Read the Sheet, only one is read, if it is multiple sheets, you may need to use objects to store the data of each sheet
          // The read result is converted into a json object, and then resolved
          for (const sheet in stores.Sheets) {
            if (stores.Sheets.hasOwnProperty(sheet)) {
              //Use sheet_to_json method to convert excel into json data
              data = data.concat(
                XLSX.utils.sheet_to_json(stores.Sheets[sheet])
              );
              break;
            }
          }
          resolve(data);
        } catch (err) {
          console.log(err, "error");
          reject(err);
        }
      };
      fileReader.readAsBinaryString(file);
    });
  };

  const importExcel = async (e) => {
    const file = e.target.files[0];
    const data = await importExcelToJson(file);
    console.log(data, "data");
    let header = [];
    for (const [key] of Object.entries(data[0])) {
      header.push(key);
    }
    console.log(header, "header");
  };

  return (
    <div>
      <p>Read Excel file to json object</p>
      <input type="file" accept=".xlsx, .xls" onChange={importExcel} />
    </div>
  );
}